package org.tang.schoolproject.service.Imp;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.tang.schoolproject.entitys.Book;
import org.tang.schoolproject.entitys.File;
import org.tang.schoolproject.entitys.User;
import org.tang.schoolproject.mapper.BookMapper;
import org.tang.schoolproject.mapper.FileMapper;
import org.tang.schoolproject.mapper.UserMapper;
import org.tang.schoolproject.entitys.properties.FileProperties;
import org.tang.schoolproject.service.BookService;
import org.tang.schoolproject.utils.FilesUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
@RequiredArgsConstructor
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    private final BookMapper bookMapper;
    private final FilesUtils filesUtils;
    private final UserMapper userMapper;
    private final FileProperties fileProperties;
    private final FileMapper fileMapper;

    /**
     * 保存书籍信息
     * @param files
     * @param book
     * @return
     */
    @Override
    public SaResult saveBook(MultipartFile[] files, Book book) {
        ArrayList<String> filePaths = new ArrayList<>();
        for (MultipartFile file : files){
            Map<String, Object> upload = filesUtils.upload(file);
            if (upload.get("filePath") == null) return SaResult.error("请传递图片格式为.jpg");
            filePaths.add(upload.get("filePath").toString());
        }
        book.setCoverImage(filePaths.get(0));
        book.setBackImage(filePaths.get(1));
        //提交用户
        String loginId = StpUtil.getLoginId().toString();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, loginId);
        User user = userMapper.selectOne(wrapper);
        if (user == null) return SaResult.error("未查询出当前用户");
        book.setSubmitUser(user.getId());
        return bookMapper.insert(book)>0? SaResult.ok("保存成功") : SaResult.error("保存失败");
    }

    /**
     * 根据id查询书籍信息
     * @param id
     * @return
     */
    @Override
    public SaResult getBookById(Long id) {
        Book book = bookMapper.selectById(id);
        if (book == null) return SaResult.error("未查询到书籍信息");
        book.setCoverImage(book.getCoverImage().replace(fileProperties.getImgAddress(),fileProperties.getImgHttpAddress()));
        book.setBackImage(book.getBackImage().replace(fileProperties.getImgAddress(),fileProperties.getImgHttpAddress()));
        //todo:书籍内容添加
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId, book.getId());
        File file = fileMapper.selectOne(wrapper);
        book.setFileName(file);
        return SaResult.data(book);
    }

    /**
     * 保存书籍内容
     * @param file
     * @param bookId
     * @return
     */
    @Override
    public SaResult saveBookContent(MultipartFile file, Long bookId) {
        Map<String, Object> upload = filesUtils.upload(file);
        if (upload.get("filePath") == null) return SaResult.error("请传递文件格式为.pdf");
        File file1 = File.builder()
                .bookId(bookId)
                .pathFileName(upload.get("fileName").toString())
                .build();
        return SaResult.data(file1);
    }

    /**
     * 修改书籍信息
     * @param files
     * @param book
     * @return
     */
    @Override
    public SaResult updateBook(MultipartFile[] files, Book book) {
        Book book1 = bookMapper.selectById(book.getId());
        if (book1 == null) return SaResult.error("未查询到书籍信息");
        if (files != null && files[0] != null){
            Map<String, Object> upload = filesUtils.upload( files[0]);
            book.setCoverImage(upload.get("filePath").toString());
        }
        if (files != null && files[1] != null){
            Map<String, Object> upload = filesUtils.upload( files[1]);
            book.setBackImage(upload.get("filePath").toString());
        }
        return bookMapper.updateById(book) > 0 ? SaResult.ok("修改成功") : SaResult.error("修改失败");
    }

    /**
     * 修改书籍内容
     * @param file
     * @param bookId
     * @return
     */
    @Override
    public SaResult updateBookContent(MultipartFile file,Long bookId) {
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId, bookId);
        File file1 = fileMapper.selectOne(wrapper);
        if (file1 == null) return SaResult.error("未查询到书籍内容");
        Map<String, Object> upload = filesUtils.upload(file);
        if (upload.get("filePath") == null) return SaResult.error("请传递文件格式为.pdf");
        File filePath = File.builder()
                .bookId(bookId)
                .pathFileName(upload.get("fileName").toString())
                .build();
        UpdateWrapper<File> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("book_id", bookId).set("path_file_name",filePath);
        return fileMapper.update(filePath, updateWrapper) > 0 ? SaResult.ok("修改成功") : SaResult.error("修改失败");
    }

    /**
     * 删除书籍信息
     * @param id
     * @return
     */
    @Override
    public SaResult deleteBook(Long id) {
        Book book = bookMapper.selectById(id);
        if (book == null) return SaResult.error("未查询到书籍信息");
        //删除书籍信息
        bookMapper.deleteById( id);
        filesUtils.deleteFile(book.getCoverImage());
        filesUtils.deleteFile(book.getBackImage());
        //删除书籍内容
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId, id);
        File file = fileMapper.selectOne(wrapper);
        if (file != null) {
            fileMapper.deleteById( file.getId());
            filesUtils.deleteFile(file.getPathFileName());
        }
        return SaResult.ok("删除成功");
    }

    /**
     * 根据书籍id查询书籍内容
     * @param bookId
     * @return
     */
    @Override
    public SaResult fileByBookId(Long bookId) {
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(File::getBookId, bookId);
        File file = fileMapper.selectOne(wrapper);
        return SaResult.data(file);
    }

    @Override
    public List<String> getImagesNames() {
        List<String> list = new ArrayList<>();
        List<Book> books = bookMapper.selectList(null);
        for (Book book : books) {
            list.add(book.getBackImage().substring(book.getBackImage().lastIndexOf("/") + 1));
            list.add(book.getCoverImage().substring(book.getCoverImage().lastIndexOf("/") + 1));
        }
        return list;
    }

}
